package com.lambkit.core;

import com.lambkit.core.pipeline.PipeLine;
import com.lambkit.core.pipeline.PipeLineContext;
import com.lambkit.core.pipeline.Valve;

public class AppRunningPipLine {
    private PipeLine pipLine;

    public AppRunningPipLine() {
        this.pipLine = new PipeLine();
    }

    public static AppRunningPipLine by(Valve valve) {
        AppRunningPipLine task = new AppRunningPipLine();
        task.addValve(valve);
        return task;
    }

    public AppRunningPipLine addValve(Valve valve) {
        if(getPipLine()!=null) {
            getPipLine().addValve(valve);
        }
        return this;
    }

    public PipeLineContext invoke() {
        PipeLineContext context = null;
        if(getPipLine()!=null) {
            context = new PipeLineContext();
            getPipLine().invoke(context);
        }
        return context;
    }

    public void invoke(PipeLineContext context) {
        if(getPipLine()!=null) {
            getPipLine().invoke(context);
        }
    }

    public Valve firstValve() {
        if(getPipLine()==null) {
            return null;
        }
        return getPipLine().firstValve();
    }

    public Valve endValue() {
        if(getPipLine()==null) {
            return null;
        }
        Valve valve = getPipLine().firstValve();
        Valve result = valve;
        while (valve != null) {
            result = valve;
            valve = (Valve) valve.getNext();
        }
        return result;
    }

    public PipeLine getPipLine() {
        return pipLine;
    }

    public void setPipLine(PipeLine pipLine) {
        this.pipLine = pipLine;
    }
}
